<script>
import {
  TABLE_FIELD_QUARTER, TABLE_FIELD_YEAR,
} from '@/config'
import {
  loadEnergyConsumptionStructureSchedule,
} from '@/api/enterpriseQuarterlyReport'
import EnergyTableMixin from '@/components/quarterly-account-table/energy-table-mixin'
import ArrowSelectMixin from '@/components/quarterly-account-table/arrow-select-mixin'
import { selectEnergyDiscountList } from '@/api/energyDiscount'
import { uuid } from '@/utils'

import HeadEnergyConsumptionStructureSubTable from './head-energy-consumption-structure-sub-table.vue'

/* eslint quote-props: 0 */
function checkUnEdit(key, data) {
  const maps = {
    '原煤': ['refining', 'naturalGasLiquefaction', 'conversionOutput'],
    '洗精煤': ['rawCoalIsWashed', 'refining', 'naturalGasLiquefaction'],
    '其它洗煤': ['rawCoalIsWashed', 'refining', 'naturalGasLiquefaction'],
    '煤制品': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction'],
    '#：型煤': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction'],
    '水煤浆': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction'],
    '煤粉': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction'],
    '焦炭': ['rawCoalIsWashed', 'refining', 'naturalGasLiquefaction'],
    '其他焦化产品': ['rawCoalIsWashed', 'refining', 'naturalGasLiquefaction'],
    '焦炉煤气': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '高炉煤气': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '其他煤气': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '天然气': ['rawCoalIsWashed', 'coking', 'refining', 'gasProduction', 'processedCoalProducts', 'conversionOutput'],
    '液化天然气': ['rawCoalIsWashed', 'coking', 'refining', 'gasProduction', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '原油': ['rawCoalIsWashed', 'naturalGasLiquefaction', 'processedCoalProducts', 'conversionOutput'],
    '汽油': ['heating', 'rawCoalIsWashed', 'coking', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '煤油': ['heating', 'rawCoalIsWashed', 'coking', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '柴油': ['rawCoalIsWashed', 'coking', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '燃料油': ['rawCoalIsWashed', 'coking', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '液化石油气': ['rawCoalIsWashed', 'coking', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '炼厂干气': ['rawCoalIsWashed', 'coking', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '其他石油制品': ['rawCoalIsWashed', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '热力': ['rawCoalIsWashed', 'coking', 'refining', 'gasProduction', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '电力': ['thermalPowerGeneration', 'heating', 'rawCoalIsWashed', 'coking', 'refining', 'gasProduction', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '其他燃料': ['rawCoalIsWashed', 'naturalGasLiquefaction'],
    '#：煤矸石': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction'],
    '生物质能': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction', 'processedCoalProducts'],
    '工业废料': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction'],
    '城市固体垃圾': ['rawCoalIsWashed', 'coking', 'refining', 'naturalGasLiquefaction'],
  }
  const name = data.energyName
  const values = maps[name]
  return values ? !values.includes(key) : true
}

export default {
  name: 'energy-consumption-structure-sub-table',
  mixins: [EnergyTableMixin, ArrowSelectMixin],
  components: {
    HeadEnergyConsumptionStructureSubTable
  },
  created() {
    this.loadList = loadEnergyConsumptionStructureSchedule
  },
  data() {
    return {
      // 本年综合能源消费量（当量值）
      currentValue: '',
      // 上年综合能源消费量（当量值）
      previousValue: '',

      // 表序号
      seriesNo: '表1-2-1',
    }
  },
  computed: {
    // 消费量中的“合计"
    calc() {
      const lists = this.lists.map(v => v.data)

      // 加工转换投入合计=火力发电投入+供热投入+原煤入洗投入+炼焦投入+炼油及煤制油投入+制气投入+天然气液化投入+加工煤制品投入
      const keys = [
        'thermalPowerGeneration',
        'heating',
        'rawCoalIsWashed',
        'coking',
        'refining',
        'gasProduction',
        'naturalGasLiquefaction',
        'processedCoalProducts',
      ]

      return {
        // 加工转换投入合计
        machiningConversion: lists.map((v) => {
          let result = 0
          keys.forEach((key) => {
            const target = v.find(x => x.key === key)
            const value = +(target?.value) || 0
            result += value
          })
          result = +(result.toFixed(2))
          return Number.isFinite(result) && result > 0 ? result : ''
        }),
        conversionOutputDiscount: lists.map((v) => {
          let result = 0
          const t1 = v.find(x => x.key === 'conversionOutput')
          const t2 = v.find(x => x.key === 'useScalingFactor')
          result = (+(t1?.value)) * (+(t2?.value))
          result = +(result.toFixed(2))
          return Number.isFinite(result) && result > 0 ? result : ''
        }),
      }
    },
    summary() {
      const obj = {
        energyName: '能源合计',
        unitOfMeasurement: '',
        code: '40',
        referenceDiscountFactor: '',
      }
      const array = ['无烟煤', '炼焦烟煤', '一般烟煤', '褐煤'];
      // 原煤这一行：“工业生产消费量、加工转换投入合计、能源加工转换产出折标量三者有其一
      // 则认为原煤是有效数据，即忽略原煤的四子项（不保存、不参与能源合计）
      const has01 = this.calc.machiningConversion[0] !== '' ||
        this.calc.conversionOutputDiscount[0] !== '' ||
        this.lists.some(v => {
          const data = v.data;
          const target = data.find(vv => vv.key === 'energyName' && vv.value === '原煤')
          const t = target ? data.find(v => v.key === 'industrialProduction') : null
          return t && t.value !== ''
        })

      const lists = this.lists.filter(v => {
        const data = v.data
        // 是否是”其中“项所在行
        const isQizhong = data.some(vv => vv.key === 'energyName' && array.includes(vv.value))
        return (has01 && !isQizhong) || !has01
      }).map(v => v.data)
      // 折标系数
      const sss = lists.map(v => {
        const target = v.find(vv => vv.key === 'useScalingFactor')
        return target ? target.value : ''
      })
      const props = this.flattenColumns.map(v => v.prop)
      const listsMap = props.reduce((acc, prop) => {
        if (
          ![
            'referenceDiscountFactor', 'useScalingFactor',
            'machiningConversion', 'conversionOutputDiscount'
          ].includes(prop)
        ) {
          acc[prop] = lists.map(v => {
            const target = v.find(vv => vv.key === prop)
            return target ? target.value : ''
          })
        }
        return acc
      }, {})
      // 加工转换投入合计
      listsMap.machiningConversion = [...this.calc.machiningConversion]
      // 能源加工转换产出折标量（吨标准煤）
      listsMap.conversionOutputDiscount = [...this.calc.conversionOutputDiscount]

      // ①消费量：
      // 工业生产消费量、火力发电、供热、原煤入洗、炼焦、炼油、制气、
      // 天然气液化、加工煤制品、能源加工转换产出、回收利用、能源加工转换产出折标量（吨标准煤）、
      // 分别=能源品种×采用折标系数（累加）；

      // 能源加工转换产出折标量（吨标准煤）合计数=上列值相加；
      const accumulate = (prop, withFactor) => {
        const n = +(listsMap[prop].reduce((acc, v, i) => {
          acc += (Number.isFinite(+v) ? +v : 0) * (withFactor ? (+sss[i] || 1) : 1)
          return acc
        }, 0).toFixed(2))
        return Number.isFinite(n) ? n : ''
      }
      const getValue = (prop) => {
        if (
          [
            'industrialProduction',
            'thermalPowerGeneration',
            'heating',
            'rawCoalIsWashed',
            'coking',
            'refining',
            'gasProduction',
            'naturalGasLiquefaction',
            'processedCoalProducts',
            'conversionOutput',
            'recycleAndReuse',
          ].includes(prop)
        ) {
          // 工业生产消费量、火力发电、供热、原煤入洗、炼焦、炼油、制气、
          // 天然气液化、加工煤制品、能源加工转换产出、回收利用、能源加工转换产出折标量（吨标准煤）、
          return accumulate(prop, true)
        } else if (
          ['conversionOutputDiscount', 'machiningConversion'].includes(prop)
        ) {
          // 能源加工转换产出折标量（吨标准煤）合计数
          return accumulate(prop)
        }
      }
      const data = this.flattenColumns.map(v => {
        let editable = true
        if (
          Object.keys(obj).includes(v.prop)
        ) {
          editable = false
        }

        const value = obj[v.prop] || getValue(v.prop)

        return {
          key: v.prop,
          value: Number(value) ? Number(value).toFixed(2) : value,
          editable,
        }
      })

      const machiningConversion = data.find(v => v.key === 'machiningConversion');
      const value = data.filter(v => {
        return [
          'thermalPowerGeneration',
          'heating',
          'rawCoalIsWashed',
          'coking',
          'refining',
          'gasProduction',
          'naturalGasLiquefaction',
          'processedCoalProducts'
        ].includes(v.key)
      }).reduce((acc, vv) => {
        acc += (Number(vv.value) || 0)
        return acc
      }, 0)
      if (machiningConversion) {
        machiningConversion.value = (value ? Number(value).toFixed(2) : '')
      }

      return {
        uuid: uuid(),
        data: data
      }
    },
  },
  methods: {
    getEnergyDiscount() {
      return selectEnergyDiscountList().then(res => {
        return res.data || []
      })
    },
    transfer(lists) {
      const props = this.flattenColumns.map(v => v.prop)
      return lists.map(v => {
        return {
          uuid: uuid(),
          informant: {
            personInCharge: v.personInCharge,
            informer: v.informer,
            telephone: v.telephone,
            fillInDate: v.fillInDate,
          },
          data: props.map(vv => {
            const editable = ![
              'energyName', 'unitOfMeasurement', 'code',
              'machiningConversion', // 加工转换投入合计
              'conversionOutputDiscount', // 能源加工转换产出折标量
              'total', 'referenceDiscountFactor',
              'industrialProduction', // 表1-2-1中的工业生产消费量从表1-2中带出
            ].includes(vv) && !this.readonly && checkUnEdit(vv, v);
            return {
              key: vv,
              value: String(v[vv] || ''),
              editable,
              calculable: ['machiningConversion', 'conversionOutputDiscount'].includes(vv),
            }
          })
        }
      })
    },
    getCalc(row, prop, value) {
      const calc = this.calc
      return calc[prop]?.[row] || value
    },
    // 初始化表数据
    initLists(params) {
      // 查询企业填报的数据
      if (this.loadList) {
        params = params || {
          [TABLE_FIELD_YEAR]: this.year,
          [TABLE_FIELD_QUARTER]: this.quarter,
          tenantId: this.enterpriseId
        }
        return this.loadList(params).then(async res => {
          if (res.code === 200) {
            let data = res.data || []
            if (data.length === 0) {
              // 为空时加载默认能源名称
              const energyDiscount = await this.getEnergyDiscount()
              data = energyDiscount.map(
                /**
                 *
                 * @param v{{
                 *  id: string | number;
                 *  name: string;
                 *  discountFactorUnit: string;
                 *  referenceCoefficient: string;
                 * }}
                 * @returns {{unitOfMeasurement: (*|string), referenceDiscountFactor: (*|string), code: string, useScalingFactor: number, energyName: string}}
                 */
                v => ({
                  energyName: v.name || '',
                  unitOfMeasurement: v.discountFactorUnit ? (v.discountFactorUnit.split('/')[1]) : '吨标准煤',
                  useScalingFactor: Math.min(
                    ...(v.referenceCoefficient || '').split('-').map(vv => +vv)
                  ),
                  referenceDiscountFactor: v.referenceCoefficient || '',
                  code: String(v.id).padStart(2, '0'),
                })
              )
            } else {
              const findIndex = data.findIndex(v => v.energyName === '能源合计' || v.code === '40')
              if (findIndex > -1) {
                data.splice(findIndex, 1)
              }
            }
            this.lists = this.transfer(data)

            // 本年综合能源消费量（当量值）
            // 上年综合能源消费量（当量值）
            const item = data[0]
            if (item) {
              this.currentValue = String(item.consumptionThisYear || '')
              this.previousValue = String(item.consumptionLastYear || '')
            }

            this.$nextTick(() => {
              this.initInputIndex()
            })
          }
        }).catch(() => {
          console.log('reject')
          this.$nextTick(() => {
            this.initInputIndex()
          })
        })
      }
    },
  },
}
</script>

<template>
  <div class="bg-white height-100 quarterly-account-table position-relative overflow-hidden">
    <slot name="title" :title="title" :series-no="seriesNo">
      <h2 class="table-title">
        {{ title }}
      </h2>
    </slot>
    <div class="report-table-head">
      <!-- <table class="report-table">
        <table-head :columns="columns" :show-line-number="showLineNumber"></table-head>
      </table> -->
      <HeadEnergyConsumptionStructureSubTable></HeadEnergyConsumptionStructureSubTable>
    </div>
    <el-scrollbar :style="{ height: 'calc(100% - 160px)' }" wrap-style="overflow-x: hidden;">
      <table class="report-table">
        <tbody ref="tbody">
          <tr v-for="(item, i) in lists" :key="item.uuid">
            <th v-if="showLineNumber" class="readonly width-40px line-number">{{ i + 1 }}</th>
            <td v-for="(d, index) in item.data" :key="item.uuid + index" :class="{
              'readonly': !d.editable,
              'is-calculable': d.calculable || d.key === 'industrialProduction',
            }">
              <div v-if="!d.editable" class="span-cell">
                {{ d.calculable ? calc[d.key][i] : d.value }}
              </div>
              <div v-else class="input-cell">
                <input type="text" v-model="d.value" @click="clickHandler">
              </div>
            </td>
          </tr>
          <tr class="readonly">
            <th v-if="showLineNumber" class="readonly width-40px line-number">{{ lists.length + 1 }}</th>
            <td v-for="(item, index) in summary.data" :key="summary.uuid + index">
              <div class="span-cell">
                {{ item.value }}
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="flex extra-fill">
        <div class="report-label is-required">本年综合能源消费量（当量值）：</div>
        <div class="report-value">
          <input type="text" :disabled="readonly" class="report-input" v-model="currentValue">
        </div>
        <div class="report-unit">万吨标准煤</div>
        <div class="report-label is-required">上年综合能源消费量（当量值）：</div>
        <div class="report-value">
          <input type="text" :disabled="readonly" class="report-input" v-model="previousValue">
        </div>
        <div class="report-unit">万吨标准煤</div>
      </div>
      <report-person ref="reportPerson" :informer="informant" :readonly="readonly"></report-person>
      <div v-if="tableDescription" class="fill-description">
        <template>
          <!-- <p>说明：</p>
          <p>1．计算“能源加工转换产出”、“回收利用”指标使用的折算系数同表1-2</p>
          <p>2．主要逻辑审核关系：</p>
          <p class="padding-horizontal">(1) 工业生产消费量与表1-2的工业生产消费量数值一致。</p>
          <p class="padding-horizontal">(2) 加工转换投入合计=火力发电投入+供热投入+原煤入洗投入+炼焦投入+炼油及煤制油投入+制气投入+天然气液化投入+加工煤制品投入。</p>
          <p>3．能源合计=∑某种能源×某种能源折标准煤系数（不重复计算“其中”项）。</p> -->

          <el-input type="textarea" class="width-100 table-description" :value="tableDescription" readonly
            autosize></el-input>
        </template>
      </div>
    </el-scrollbar>
  </div>
</template>

<style scoped>
.extra-fill {
  align-items: center;
  margin-top: 12px;
  font-size: 12px;
  padding: 0 12px;

  --height: 33px;
}

.report-label {
  font-weight: 600;
  color: #333;
}

.report-value {
  border-bottom: 1px solid #999;
}

.report-unit {
  margin-right: 1rem;
}

.report-value ::v-deep .el-input__inner {
  border: none;
  background: transparent;
  height: auto;
  line-height: 1.15;
  padding: 0;
}

.report-input {
  border: none;
  outline: none;
  background: transparent;
  vertical-align: bottom;
}
</style>
